﻿using EasyCore.UnitOfWork;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyAdmin.DatabaseAccessor.SqlSugar
{
    /// <summary>
    /// SQLSugar事务与工作单元
    /// </summary>
    public class SqlSugarUnitOfWork : IUnitOfWork
    {
        /// <summary>
        /// slqSugar对象
        /// </summary>
        private readonly ISqlSugarClient _sqlSugarClient;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarClient"></param>
        public SqlSugarUnitOfWork(ISqlSugarClient sqlSugarClient)
        {
            this._sqlSugarClient = sqlSugarClient;
        }

        /// <summary>
        /// 开始工作单元管理
        /// </summary>
        public void BeginTransaction()
        {
            _sqlSugarClient.AsTenant().BeginTran();
        }

        /// <summary>
        /// 提交工作单元处理
        /// </summary>
        public void CommitTransaction()
        {
            _sqlSugarClient.AsTenant().CommitTran();
        }

        /// <summary>
        /// 执行完毕（无论成功失败）
        /// </summary>
        public void OnCompleted()
        {
            _sqlSugarClient.Dispose();
        }

        /// <summary>
        /// 回滚工作单元处理
        /// </summary>
        public void RollbackTransaction()
        {
            _sqlSugarClient.AsTenant().RollbackTran();
        }
    }
}
